package com.spzx.user.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.context.SecurityContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spzx.user.mapper.UserAddressMapper;
import com.spzx.user.api.domain.UserAddress;
import com.spzx.user.service.IUserAddressService;

/**
 * 用户地址Service业务层处理
 *
 * @author lee
 * @date 2024-07-23
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService
{
    @Autowired
    private UserAddressMapper userAddressMapper;

    /**
     * 查询用户地址列表
     *
     * @param userAddress 用户地址
     * @return 用户地址
     */
    @Override
    public List<UserAddress> selectUserAddressList(UserAddress userAddress)
    {
        return userAddressMapper.selectUserAddressList(userAddress);
    }

    @Override
    public int saveAddress(UserAddress userAddress) {
        Long isDefault = userAddress.getIsDefault();
        Long userId = SecurityContextHolder.getUserId();
        userAddress.setUserId(userId);
        if (isDefault == 1){
            //将其他的默认地址改为否
            List<UserAddress> addressList = baseMapper.selectList(
                    new LambdaQueryWrapper<UserAddress>().eq(UserAddress::getUserId, userId)
                            .eq(UserAddress::getIsDefault, 1));
            addressList.forEach(address ->{
                address.setIsDefault(0L);
            });
            addressList.add(userAddress);
            this.saveOrUpdateBatch(addressList);
        }
        return baseMapper.insert(userAddress);
    }

    @Override
    public int updateAddress(UserAddress userAddress) {
        Long isDefault = userAddress.getIsDefault();
        Long userId = SecurityContextHolder.getUserId();
        if (isDefault == 1){
            //将其他的默认地址改为否
            List<UserAddress> addressList = baseMapper.selectList(
                    new LambdaQueryWrapper<UserAddress>().eq(UserAddress::getUserId, userId)
                            .eq(UserAddress::getIsDefault, 1));
            addressList.forEach(address ->{
                address.setIsDefault(0L);
            });
            addressList.add(userAddress);
            this.saveOrUpdateBatch(addressList);
        }
        return baseMapper.updateById(userAddress);
    }

}
